﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Facebook.Components;
using Facebook.Exceptions;

namespace GNUGo.Net.WebApp {
	public partial class _Default : System.Web.UI.Page {
		private const string FACEBOOK_API_KEY = "46f49f2ca0c35480de66406438e6e2b5";
		private const string FACEBOOK_SECRET = "c5bac31a77d9ff826c26bbe65cfa6bf9";

		FacebookService _fbService = new FacebookService();

		protected void Page_Load(object sender, EventArgs e) {
			_fbService.ApplicationKey = FACEBOOK_API_KEY;
			_fbService.Secret = FACEBOOK_SECRET;
			_fbService.IsDesktopApplication = false;

			string sessionKey = Session["facebook_session_key"] as String;
			string userId = Session["facebook_userId"] as String;

			// When the user uses the facebook login page, the redirect back here will will have the auth_token in the query params
			string authToken = Request.QueryString["auth_token"];

			// We have already established a session on behalf of this user
			if (!String.IsNullOrEmpty(sessionKey)) {
				_fbService.SessionKey = sessionKey;
				_fbService.UserId = userId;
			// This will be executed when facebook login redirects to our page
			} else if (!String.IsNullOrEmpty(authToken)) {
				try {
					_fbService.CreateSession(authToken);
					Session["facebook_session_key"] = _fbService.SessionKey;
					Session["facebook_userId"] = _fbService.UserId;
					Session["facebook_session_expires"] = _fbService.SessionExpires;
				} catch (FacebookException) {
					Response.Redirect(@"http://www.facebook.com/login.php?api_key=" + _fbService.ApplicationKey + @"&v=1.0");
				}
			// Need to login
			} else {
				Response.Redirect(@"http://www.facebook.com/login.php?api_key=" + _fbService.ApplicationKey + @"&v=1.0");
			}

			sessionKeyHiddenField.Value = _fbService.SessionKey;
			userIdHiddenField.Value = _fbService.UserId;
		}
	}
}
